import 'dart:developer';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_document/components/qrcode_scan/flash.dart';
import 'package:qr_code_scanner/qr_code_scanner.dart';
import 'package:flutter_document/components/qrcode_scan/album.dart';

class QRCode extends StatefulWidget {
  const QRCode({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _QRCodeState();
}

class _QRCodeState extends State<QRCode> {
  Barcode? result;
  QRViewController? controller;
  final GlobalKey qrKey = GlobalKey(debugLabel: 'QR');

  // In order to get hot reload to work we need to pause the camera if the platform
  // is android, or resume the camera if the platform is iOS.
  @override
  void reassemble() {
    super.reassemble();
    if (Platform.isAndroid) {
      controller!.pauseCamera();
    }
    controller!.resumeCamera();
  }

  @override
  Widget build(BuildContext context) {
    // 状态栏高度
    double statusBarHeight = MediaQuery.of(context).padding.top;

    return Scaffold(
      body: Stack(
        children: [
          _buildQrView(context),
          // 返回按钮
          Positioned(
            top: statusBarHeight + 20,
            left: 10,
            child: IconButton(
              color: Colors.white,
              iconSize: 30,
              icon: Icon(Icons.arrow_back),
              onPressed: () {
                Navigator.pop(context);
              },
            ),
          ),
          // 闪光灯按钮
          FlashToggle(controller: controller),
          // 相册
          const Positioned(
            right: 30,
            bottom: 30,
            child: Album(iconSize: 45,),
          )
        ],
      ),
    );
  }

  void _showBottomSheet(BuildContext context) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('提示'),
          content: result?.code != null? Text(result!.code!) : Text(''),
          actions: <Widget>[
            TextButton(
              child: Text('取消'),
              onPressed: () {
                // 滞空result
                result = null;
                // 关闭弹框
                Navigator.of(context).pop();
                // 恢复扫描
                controller?.resumeCamera();
              },
            ),
            TextButton(
              child: Text('跳转'),
              onPressed: () {
                // 滞空result
                result = null;
                // 在这里添加用户点击"确定"按钮后的逻辑
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }

  Widget _buildQrView(BuildContext context) {
    // For this example we check how width or tall the device is and change the scanArea and overlay accordingly.
    var scanArea = (MediaQuery.of(context).size.width < 500 ||
            MediaQuery.of(context).size.height < 500)
        ? 250.0
        : 400.0;
    // To ensure the Scanner view is properly sizes after rotation
    // we need to listen for Flutter SizeChanged notification and update controller
    return QRView(
      key: qrKey,
      onQRViewCreated: _onQRViewCreated,
      overlay: QrScannerOverlayShape(
          borderColor: Colors.red,
          borderRadius: 10,
          borderLength: 30,
          borderWidth: 10,
          cutOutSize: scanArea),
      onPermissionSet: (ctrl, p) => _onPermissionSet(context, ctrl, p),
    );
  }

  void _onQRViewCreated(QRViewController controller) {
    setState(() {
      this.controller = controller;
    });
    controller.scannedDataStream.listen((scanData) {
      setState(() {
        result = scanData;

        // 停止扫描
        controller.pauseCamera();

        _showBottomSheet(context);
      });
    });
  }

  void _onPermissionSet(BuildContext context, QRViewController ctrl, bool p) {
    log('${DateTime.now().toIso8601String()}_onPermissionSet $p');
    if (!p) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('no Permission')),
      );
    }
  }

  @override
  void dispose() {
    controller?.dispose();
    super.dispose();
  }
}
